package com.xiaowu.netmusic.config;

import com.xiaowu.netmusic.filter.JwtAuthenticationFilter;
import com.xiaowu.netmusic.handler.CustomAuthenticationEntryPoint;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@RequiredArgsConstructor // 更好用的 Lombok 注解，自动生成有参构造器（替换掉 AllArgsConstructor）
public class SecurityConfig {

    private final AccessDeniedHandler accessDeniedHandler;
    private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    private final UserDetailsService userDetailsService;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(AbstractHttpConfigurer::disable) // 禁用 CSRF
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(
                                "/user/login",
                                "/user/register",
                                "/user/captcha",
                                "/user/upload/**",
                                "/doc.html",
                                "/oauth2/**",
                                "/webjars/**",
                                "/v3/**",
                                "/user/**"
                        ).permitAll() // 放行这些接口
                        .anyRequest().authenticated() // 其他全部需要认证
                )
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) // 加 JWT 过滤器
                .exceptionHandling(exceptionHandling -> exceptionHandling
                        .authenticationEntryPoint(customAuthenticationEntryPoint) // 自定义认证异常
                        .accessDeniedHandler(accessDeniedHandler) // 自定义授权异常
                )
                .cors(cors -> cors.configurationSource(corsConfigurationSource())) // 自定义 CORS 配置

        // 如果需要 OAuth2 登录，取消下面的注释
        .oauth2Login(oauth2 -> oauth2
            .loginPage("/login/oauth2/code/github") // 如果有自定义登录页的话
        );

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(); // 使用 BCrypt 加密
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager(); // 获取默认 AuthenticationManager
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 允许你的前端域名跨域访问（实际根据你的前端地址改一下）
        configuration.setAllowedOriginPatterns(Arrays.asList(
                "http://localhost:8222",
                "http://127.0.0.1:8222",
                "https://your-frontend-domain.com"
        ));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true); // 允许带上 Cookie 认证信息
        configuration.setMaxAge(3600L); // 预检请求缓存时间1小时

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration); // 应用到所有接口
        return source;
    }
}
